package com.hilin.hilinim.netty.ws.etcd;

import com.hilin.hilinim.netty.ws.WsMsgReceive;
import lombok.extern.slf4j.Slf4j;
import mousio.etcd4j.EtcdClient;
import mousio.etcd4j.requests.EtcdKeyGetRequest;
import mousio.etcd4j.responses.EtcdKeysResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class HilinEtcdMqConfig {

    public static final String EK_MSG_LISTENER = "/com/hilin/im/msg/receive";

    private static final long[] MODIFIED_INDEX = {0};

    public static Thread msg_thread;

    @Autowired
    private WsMsgReceive wsMsgReceive;

    @Autowired
    public void initMsgThread(EtcdClient client) {
        if (msg_thread == null) {
            msg_thread = new Thread(() -> {
                while (true) {
                    try {
                        EtcdKeyGetRequest request = client.get(EK_MSG_LISTENER);
                        if (!(MODIFIED_INDEX[0] == 0)) {
                            request.waitForChange();
                        }
                        EtcdKeysResponse response = request.send().get();
                        MODIFIED_INDEX[0] = response.node.modifiedIndex + 1;
                        wsMsgReceive.onMessage(response.node.value);
                    } catch (Exception e) {
                        log.error("消息接收访问失败", e);
                        // 访问失败，暂停500毫秒
                        try {
                            Thread.sleep(500);
                        } catch (Exception ignored) {
                        }
                    }
                }
            });
            msg_thread.start();
        }
    }

}
